/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.view;

import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ElementScatter;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.KeyEvent;

import com.xuexiang.xui_lib.util.KeyboardUtils;
import com.xuexiang.xuidemo.ResourceTable;

/**
 * 只封装搜索框
 *
 * @since 2021-03-29
 */
public class SearchCompoent extends DirectionalLayout implements Component.ClickedListener {
    private EventHandler handler = new EventHandler(EventRunner.create(true));
    private Context context;
    private Image onebase;
    private Image oneimg;
    private Image twoimg;
    private Image twoimgclose;
    private Text onetext;
    private Text bottomtext;
    private Text textbace;
    private DependentLayout oneSearlayout;
    private DependentLayout twoSearlayout;
    private ComponentContainer backgroud;
    private ComponentContainer botomlayout;
    private TextField twoField;
    private boolean isJudge = true;
    private String data;
    private float movestart;
    private boolean isInfo = true;
//    private AnimatorProperty animatorProperty;
    private static final int anInt60 = 60;
    private static final int anInt2000 = 2000;
    private int height;

    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public SearchCompoent(Context context) {
        super(context);
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrSet 样式
     */
    public SearchCompoent(Context context, AttrSet attrSet) {
        super(context, attrSet);
        this.context = context;
        initview();
        initdata();
    }

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrSet 样式
     * @param styleName 名字
     */
    public SearchCompoent(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    private void initview() {
        height = AttrHelper.vp2px(anInt60, context);
        Component ct = LayoutScatter.getInstance(getContext())
            .parse(ResourceTable.Layout_searcompoent_layout, this, true);
        oneSearlayout = (DependentLayout) ct.findComponentById(ResourceTable.Id_One_Searlayout);
        twoSearlayout = (DependentLayout) ct.findComponentById(ResourceTable.Id_Two_searlayout);
        onebase = (Image) ct.findComponentById(ResourceTable.Id_One_base);
        onebase.setClickedListener(this::onClick);
        oneimg = (Image) ct.findComponentById(ResourceTable.Id_One_img);
        oneimg.setClickedListener(this::onClick);
        twoimg = (Image) ct.findComponentById(ResourceTable.Id_Two_img);
        twoimg.setClickedListener(this::onClick);
        twoimgclose = (Image) ct.findComponentById(ResourceTable.Id_Two_imgclose);
        twoimgclose.setClickedListener(this::onClick);
        onetext = (Text) ct.findComponentById(ResourceTable.Id_One_text);
        textbace = (Text) ct.findComponentById(ResourceTable.Id_Text_bace);
        twoField = (TextField) ct.findComponentById(ResourceTable.Id_Two_field);
        twoField.addTextObserver(new Text.TextObserver() { // 字体变化监听
            @Override
            public void onTextUpdated(String string, int i, int i1, int i2) {
                isJudge = true;
                twoimgclose.setVisibility(Component.VISIBLE);
                data = string;
            }
        });
    }

    private void initdata() {
        twoField.setKeyEventListener(new KeyEventListener() {
            @Override
            public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
                if (isJudge && data.length() > 0) {
                    isJudge = false;
                    botomlayout.setVisibility(Component.VISIBLE);
                    bottomtext.setText("Query:" + data);
                    twoField.clearFocus(); // 焦点消失,软键盘就会隐藏
                    if (isInfo) {
                        isInfo = false;
                        movestart = botomlayout.getContentPositionY();
                    }
                    AnimatorProperty property = new AnimatorProperty();
                    property.moveFromY(movestart + height);
                    property.moveToY(movestart); // 距离位置
                    property.setTarget(botomlayout); // 基于那个控件
                    property.setDuration(anInt2000);
                    property.start();
                    handler.postTask(new Runnable() {
                        @Override
                        public void run() {
                            getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    AnimatorProperty property = new AnimatorProperty();
                                    property.moveFromY(movestart); // 开始距离y轴的距离
                                    property.moveToY(movestart + height); // 结束距离位置
                                    property.setTarget(botomlayout);
                                    property.setDuration(anInt2000);
                                    property.start();
                                }
                            });
                        }
                    }, anInt2000);
                }
                return false;
            }
        });
    }

    /**
     * 设置标题栏的文本
     *
     * @param connet 文本内容
     */
    public void setText(String connet) {
        onetext.setText(connet);
    }

    /**
     * 输入框的值
     *
     * @param connent 设置输入框的hint值
     */
    public void setHide(String connent) {
        twoField.setHint(connent);
    }

    /**
     * 显示左侧不显示中间
     *
     * @param leftConnent 左侧标题内容
     */
    public void setHideimg(String leftConnent) {
        onebase.setVisibility(Component.HIDE);
        onetext.setVisibility(Component.HIDE);
        textbace.setVisibility(Component.VISIBLE);
        textbace.setText(leftConnent);
    }

    /**
     * 回调方法不提供到外面
     *
     * @param component 页面布局
     * @param component1 全局布局
     * @param component2 显示的文本
     */
    public void setComponent(ComponentContainer component, ComponentContainer component1, Text component2) {
        this.botomlayout = component;
        this.backgroud = component1;
        this.bottomtext = component2;
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_Two_imgclose: // 叉号图标
                twoField.setText("");
                twoimgclose.setVisibility(Component.HIDE);
                botomlayout.setVisibility(Component.HIDE);
                Element element2 = ElementScatter.getInstance(context)
                    .parse(ResourceTable.Graphic_backfroud_search);
                backgroud.setBackground(element2);
                break;
            case ResourceTable.Id_One_base: // 返回图标
                context.terminateAbility();
                break;
            case ResourceTable.Id_One_img: // 搜索框
                oneSearlayout.setVisibility(Component.HIDE);
                twoSearlayout.setVisibility(Component.VISIBLE);
                Element element1 = ElementScatter.getInstance(context)
                    .parse(ResourceTable.Graphic_background_page1);
                backgroud.setBackground(element1);
                twoField.setFocusable(FOCUS_ENABLE);
                twoField.requestFocus(); // 自动选中
                KeyboardUtils.showSoftInput(); // 唤起键盘
                break;
            case ResourceTable.Id_Two_img: // 返回的箭头
                twoField.setText("");
                oneSearlayout.setVisibility(Component.VISIBLE);
                twoSearlayout.setVisibility(Component.HIDE);
                Element element = ElementScatter.getInstance(context)
                    .parse(ResourceTable.Graphic_backfroud_search);
                backgroud.setBackground(element);
                KeyboardUtils.hideSoftInput(); // 关闭键盘
                break;
            default:
                break;
        }
    }
}
